package com.huawei.cartservice.service.impl;


import com.huawei.cartservice.client.ItemClient;
import com.huawei.cartservice.mapper.CartMapper;
import com.huawei.cartservice.pojo.dto.cartDTO;
import com.huawei.cartservice.pojo.entity.cart;
import com.huawei.cartservice.pojo.vo.cartVO;
import com.huawei.cartservice.service.CartService;
import com.huawei.common.pojo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ItemClient itemClient;
    @Override
    public Result addCart(List<cartDTO> cartDTO) {
        List<cart> carts = new ArrayList<>();
        for(cartDTO cartdto : cartDTO){
            cart cart = new cart();
            BeanUtils.copyProperties(cartdto,cart);
            cart.setCreateTime(LocalDateTime.now());
            carts.add(cart);
        }
        cartMapper.addCart(carts);
        return new Result(0,"添加购物车成功",null);
    }

    @Override
    public Result deleteCart(Long id) {
        cartMapper.deleteCart(id);
        return new Result(0,"删除购物车成功",null);
    }

    @Override
    public Result getCart(String token,Long id) {
        List<cart> carts = cartMapper.getCart(id);
        List<cartVO> cartVOS = new ArrayList<>();
        for(cart cart : carts){
            Result result = itemClient.getItemById(token,cart.getItemId());
            Object data = result.getData();
            Map<String,Object> map = (Map<String,Object>)data;

            cartVO cartvo = new cartVO();
            BeanUtils.copyProperties(cart,cartvo);
            cartvo.setName((String)map.get("name"));
            cartvo.setPrice((int)map.get("price"));
            cartvo.setImage((String)map.get("image"));
            cartvo.setDescription((String)map.get("description"));
            cartVOS.add(cartvo);
        }
        return new Result(0,"查询购物车成功",cartVOS);
    }


}
